package com.example.sunmiv1.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;


import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.AllocationTubeListAdapter;
import com.example.sunmiv1.base.BaseActivity;
import com.example.sunmiv1.entity.AllocationTubeBean;
import com.example.sunmiv1.entity.StatusBean;
import com.example.sunmiv1.utils.LogUtil;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


// 貨流管理.門店調撥列表  頁面
public class AllocationTubeListActvity extends BaseActivity {

    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.view_bg_top)
    View viewBgTop;
    @BindView(R.id.spr_status)
    Spinner sprStatus;
    @BindView(R.id.tv_start_time)
    TextView tvStartTime;
    @BindView(R.id.ed_start_time)
    TextView edStartTime;
    @BindView(R.id.tv_end_time)
    TextView tvEndTime;
    @BindView(R.id.ed_end_time)
    TextView edEndTime;
    @BindView(R.id.ed_order_num_search)
    EditText edOrderNumSearch;
    @BindView(R.id.iv_search)
    ImageView ivSearch;
    @BindView(R.id.rv)
    RecyclerView rv;

    private static final int GET_ERROR_STATUS = 0x000a;
    private static final int GET_INFO_ALLO_TUBE = 0x000b;
    private static final int GET_INFO_ALLO_TUBE_2 = 0x000c;
    private static final int POST_ALLO_ACTION = 0x000d;
    @BindView(R.id.btn_to_top)
    ImageView btnToTop;

    private ACache aCache;// 緩存
    private LoadingDialog loadingDialog;
    private List<AllocationTubeBean.DataBean> dataBeanList;

    private List<String> sprStatusList;  // 狀態列表
    private static ArrayAdapter sprAdapter; // 狀態列表spinner適配器
    private static AllocationTubeListAdapter adapter;

    private int page;
    private int limit;
    private String startTime;// 開始時間
    private String endTime;//結束時間
    private String edAlloOrderNum;// 調撥單號
    private static String status="";// 審覈狀態  0：未審覈  1：通過  2：失敗

    private static int verifyPosition=-1; // 執行審覈操作的item的position

    @SuppressLint("HandlerLeak")
    private static Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case GET_INFO_ALLO_TUBE:
                    adapter.notifyDataSetChanged();
                    break;
                case GET_ERROR_STATUS:
                    break;
                case GET_INFO_ALLO_TUBE_2:
                    adapter.notifyDataSetChanged();
                    break;
                case POST_ALLO_ACTION:
//                    if("0".equals(status)) {
//                        if (-1 != verifyPosition)
//                            adapter.notifyItemRemoved(verifyPosition);
//                    }else{
//                        if (-1 != verifyPosition)
//                            adapter.notifyDataSetChanged();
//                    }
                    break;
            }
        }
    };

    @OnClick({R.id.title_back, R.id.ed_start_time, R.id.ed_end_time, R.id.iv_search,R.id.btn_to_top})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.ed_start_time:
                edOrderNumSearch.setCursorVisible(false);
                getDateFromDatePickerDialog(edStartTime);
                startTime = edStartTime.getText().toString();
                break;
            case R.id.ed_end_time:
                edOrderNumSearch.setCursorVisible(false);
                getDateFromDatePickerDialog(edEndTime);
                endTime = edEndTime.getText().toString();
                break;
            case R.id.iv_search:
                edAlloOrderNum = edOrderNumSearch.getText().toString().trim();
                getAlloTubeList();
                break;
            case R.id.btn_to_top:
                rv.smoothScrollToPosition(0);
                break;
        }
    }


    @Override
    protected void initView() {
        setContentView(R.layout.activity_allocation_tube_list);
        ButterKnife.bind(this);
        aCache = ACache.get(this);
        loadingDialog = new LoadingDialog(this);
        titleTitle.setText(R.string.allocationTubeListTitle);
        dataBeanList = new ArrayList<>();
        adapter = new AllocationTubeListAdapter(dataBeanList);
        rv.setLayoutManager(new LinearLayoutManager(this));
        rv.setAdapter(adapter);
        initSpinner();
    }

    @Override
    protected void initData() {
        startTime = "";
        endTime = "";
        edAlloOrderNum = "";
        status = "";
        getAlloTubeList();
    }



    @Override
    public void initListener() {
        sprStatus.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    status = null;
                } else {
                    status = String.valueOf(position - 1);
                    LogUtil.i("此時的狀態值爲：" + status);
                }
                getAlloTubeList();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        adapter.setViewClickListener(new AllocationTubeListAdapter.ClickListener() {
            @Override
            public void setClickListener(View view, int positon) {
                switch (view.getId()) {
                    case R.id.tv_detail_to_warehouse: // 入庫詳情
                        Intent intent = new Intent(AllocationTubeListActvity.this, AllocationTubeListDetailsActivity.class);
                        intent.putExtra("activity_type", "1");
                        intent.putExtra("warehouse_record_id", dataBeanList.get(positon).getWarehouse_record_id());
                        startActivity(intent);
                        LogUtil.i("點擊事件" + "入庫詳情");
                        break;
                    case R.id.btn_accpet:// 接受/同意
                        LogUtil.i("點擊事件" + "接受/同意");
                        new AlertDialog.Builder(AllocationTubeListActvity.this).setTitle("同意")//設置對話框標題
                                .setMessage("確定要\"同意\"？")//設置顯示的內容
                                .setPositiveButton("確定", new DialogInterface.OnClickListener() {//添加確定按鈕
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {//確定按鈕的響應事件
                                        postAlloAction(dataBeanList.get(positon).getId(), "1",positon);
                                    }
                                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加取消按鈕
                            @Override
                            public void onClick(DialogInterface dialog, int which) {//取消按鈕的響應事件

                            }
                        }).show();//顯示此對話框
                        break;
                    case R.id.btn_reject:// 拒絕
                        LogUtil.i("點擊事件" + "拒絕");
                        new AlertDialog.Builder(AllocationTubeListActvity.this).setTitle("拒絕")//設置對話框標題
                                .setMessage("確定要\"拒絕\"？")//設置顯示的內容
                            .setPositiveButton("確定", new DialogInterface.OnClickListener() {//添加確定按鈕
                                @Override
                                public void onClick(DialogInterface dialog, int which) {//確定按鈕的響應事件
                                    postAlloAction(dataBeanList.get(positon).getId(), "2",positon);
                                }
                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加取消按鈕
                                @Override
                                public void onClick(DialogInterface dialog, int which) {//取消按鈕的響應事件

                                }
                            }).show();//顯示此對話框
                        break;
                    case R.id.tv_detail_allo:// 調撥詳情
                        Intent intent2 = new Intent(AllocationTubeListActvity.this, AllocationTubeListDetailsActivity.class);
                        intent2.putExtra("activity_type", "0");
                        intent2.putExtra("order_id", dataBeanList.get(positon).getId());
                        startActivity(intent2);
                        LogUtil.i("點擊事件" + "調撥細節");
                        break;
                }
            }
        });
    }

    private void postAlloAction(String id, String type,int position) {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("id", id);
            jsonObject.put("type", type);
            jsonObject.put("usertype", aCache.getAsString("userType"));
            jsonObject.put("operator_id", aCache.getAsString("operator_id"));
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.post(this, Common.ALLOCATION_EXAMINE_ACTION, jsonObject, new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                loadingDialog.dismiss();
                StatusBean data = GsonUtils.JsonToBean(text, StatusBean.class);
                if (data.getStatus() == 1) {
//                    dataBeanList.remove(position);
//                    verifyPosition=position;
//                    mHandler.sendEmptyMessage(POST_ALLO_ACTION);
                    getAlloTubeList();
                }
                Toast.makeText(AllocationTubeListActvity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
            }

            @Override
            protected void onFailure(ResponseException e) {
                loadingDialog.dismiss();
                Toast.makeText(AllocationTubeListActvity.this, "獲取數據失敗", Toast.LENGTH_SHORT).show();
            }
        });
    }

    // 初始化spinner
    private void initSpinner() {
        sprStatusList = new ArrayList<>();
        sprStatusList.add("全部狀態");
        sprStatusList.add("未審覈");
        sprStatusList.add("審覈通過");
        sprStatusList.add("審覈失敗");
        sprAdapter = new ArrayAdapter(this, R.layout.item_drop, sprStatusList);
        sprAdapter.setDropDownViewResource(R.layout.item_drops);
        sprStatus.setAdapter(sprAdapter);
    }

    /*  獲取列表*/
    private void getAlloTubeList() {
        page = 1;
        limit = 5;
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            jsonObject.put("page", page);
            jsonObject.put("limit", limit);
            jsonObject.put("order_number", edAlloOrderNum);
            jsonObject.put("start_time", edStartTime.getText().toString());
            jsonObject.put("end_time", edEndTime.getText().toString());
            jsonObject.put("examine_status", status);
            jsonObject.put("usertype", aCache.getAsString("userType"));
            jsonObject.put("operator_id", aCache.getAsString("operator_id"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.post(this, Common.ALLOCATION_TUBE_LIST, jsonObject, new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                dataBeanList.clear();
                AllocationTubeBean data = GsonUtils.JsonToBean(text, AllocationTubeBean.class);
                if (data.getStatus() == 1) {
                    dataBeanList.addAll(data.getData());
                } else {
                    Toast.makeText(AllocationTubeListActvity.this, "獲取數據失敗", Toast.LENGTH_SHORT).show();
                }
                loadingDialog.dismiss();
                mHandler.sendEmptyMessage(GET_INFO_ALLO_TUBE);
                if (dataBeanList.size() == 5)
                    getAlloTubeList2();
            }

            @Override
            protected void onFailure(ResponseException e) {
                loadingDialog.dismiss();
                Toast.makeText(AllocationTubeListActvity.this, "獲取數據失敗", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void getAlloTubeList2() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            jsonObject.put("page", 0);
            jsonObject.put("limit", 0);
            jsonObject.put("order_number", edAlloOrderNum);
            jsonObject.put("start_time", edStartTime.getText().toString().trim());
            jsonObject.put("end_time", edEndTime.getText().toString().trim());
            jsonObject.put("examine_status", status);
            jsonObject.put("usertype", aCache.getAsString("userType"));
            jsonObject.put("operator_id", aCache.getAsString("operator_id"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.post(this, Common.ALLOCATION_TUBE_LIST, jsonObject, new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                AllocationTubeBean data = GsonUtils.JsonToBean(text, AllocationTubeBean.class);
                if (data.getStatus() == 1) {
                    dataBeanList.addAll(data.getData().subList(5, data.getData().size()));
                } else {
                    Toast.makeText(AllocationTubeListActvity.this, "獲取數據失敗", Toast.LENGTH_SHORT).show();
                }
                mHandler.sendEmptyMessage(GET_INFO_ALLO_TUBE_2);
            }

            @Override
            protected void onFailure(ResponseException e) {
                Toast.makeText(AllocationTubeListActvity.this, "獲取數據失敗", Toast.LENGTH_SHORT).show();
            }
        });
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }
}
